"""电量监控模块"""
import os
import threading
import time
from .config import setup_logging

try:
    import psutil
    HAS_PSUTIL = True
except ImportError:
    HAS_PSUTIL = False

class BatteryMonitor:
    """电量监控器"""
    
    def __init__(self, tts_callback=None):
        self.logger = setup_logging('BatteryMonitor')
        self.tts_callback = tts_callback  # TTS回调函数
        self.running = False
        self.monitor_thread = None
        
        # 电量提醒阈值
        self.alert_thresholds = [50, 20]  # 50%和20%提醒
        self.alerted_levels = set()  # 已提醒的电量级别
        
        # 监控间隔（秒）
        self.check_interval = 300  # 5分钟检查一次
        
        self.logger.info("电量监控器初始化完成")
    
    def get_battery_info(self):
        """获取电量信息"""
        try:
            # 优先使用psutil获取电量信息（跨平台支持）
            if HAS_PSUTIL:
                battery = psutil.sensors_battery()
                if battery:
                    return {
                        'level': int(battery.percent),
                        'status': 'Charging' if battery.power_plugged else 'Discharging',
                        'present': True
                    }
            
            # 尝试从/sys/class/power_supply/读取电量信息（Linux系统）
            battery_path = '/sys/class/power_supply/BAT0'
            if os.path.exists(battery_path):
                return self._read_linux_battery(battery_path)
            
            # 尝试从/sys/class/power_supply/BAT1读取（某些系统）
            battery_path = '/sys/class/power_supply/BAT1'
            if os.path.exists(battery_path):
                return self._read_linux_battery(battery_path)
            
            # 如果是树莓派，尝试读取UPS模块信息
            ups_path = '/sys/class/power_supply/ups'
            if os.path.exists(ups_path):
                return self._read_linux_battery(ups_path)
            
            # 模拟电量信息（用于测试）
            self.logger.warning("未找到电池信息，使用模拟数据")
            return {
                'level': 75,  # 模拟75%电量
                'status': 'Discharging',
                'present': True
            }
            
        except Exception as e:
            self.logger.error(f"获取电量信息失败: {e}")
            return None
    
    def _read_linux_battery(self, battery_path):
        """读取Linux系统电量信息"""
        try:
            battery_info = {}
            
            # 读取电量百分比
            capacity_file = os.path.join(battery_path, 'capacity')
            if os.path.exists(capacity_file):
                with open(capacity_file, 'r') as f:
                    battery_info['level'] = int(f.read().strip())
            
            # 读取电池状态
            status_file = os.path.join(battery_path, 'status')
            if os.path.exists(status_file):
                with open(status_file, 'r') as f:
                    battery_info['status'] = f.read().strip()
            
            # 读取电池是否存在
            present_file = os.path.join(battery_path, 'present')
            if os.path.exists(present_file):
                with open(present_file, 'r') as f:
                    battery_info['present'] = f.read().strip() == '1'
            else:
                battery_info['present'] = True
            
            return battery_info
            
        except Exception as e:
            self.logger.error(f"读取电池信息失败: {e}")
            return None
    
    def get_battery_status_text(self, battery_info):
        """获取电量状态文本描述"""
        if not battery_info:
            return "电量信息不可用"
        
        level = battery_info.get('level', 0)
        status = battery_info.get('status', 'Unknown')
        
        # 电量级别描述
        if level >= 80:
            level_desc = "电量充足"
        elif level >= 50:
            level_desc = "电量良好"
        elif level >= 20:
            level_desc = "电量偏低"
        else:
            level_desc = "电量严重不足"
        
        # 充电状态描述
        if status == 'Charging':
            status_desc = "正在充电"
        elif status == 'Discharging':
            status_desc = "正在放电"
        elif status == 'Full':
            status_desc = "已充满"
        else:
            status_desc = "状态未知"
        
        return f"当前电量{level}%，{level_desc}，{status_desc}"
    
    def announce_battery_status(self):
        """播报当前电量状态"""
        battery_info = self.get_battery_info()
        if battery_info:
            status_text = self.get_battery_status_text(battery_info)
            self.logger.info(f"播报电量状态: {status_text}")
            if self.tts_callback:
                self.tts_callback(status_text)
        else:
            error_text = "无法获取电量信息"
            self.logger.warning(error_text)
            if self.tts_callback:
                self.tts_callback(error_text)
    
    def check_battery_alerts(self):
        """检查电量提醒"""
        battery_info = self.get_battery_info()
        if not battery_info:
            return
        
        level = battery_info.get('level', 0)
        status = battery_info.get('status', 'Unknown')
        
        # 只在放电状态下进行低电量提醒
        if status != 'Charging':
            for threshold in self.alert_thresholds:
                if level <= threshold and threshold not in self.alerted_levels:
                    self.alerted_levels.add(threshold)
                    alert_text = f"电量警告：当前电量{level}%，请及时充电"
                    self.logger.warning(alert_text)
                    if self.tts_callback:
                        self.tts_callback(alert_text)
        
        # 如果开始充电，清除已提醒的级别
        if status == 'Charging' and self.alerted_levels:
            self.alerted_levels.clear()
            self.logger.info("开始充电，清除电量提醒状态")
    
    def start_monitoring(self):
        """开始电量监控"""
        if self.running:
            return
        
        self.running = True
        self.monitor_thread = threading.Thread(target=self._monitor_loop)
        self.monitor_thread.daemon = True
        self.monitor_thread.start()
        self.logger.info("电量监控已启动")
    
    def stop_monitoring(self):
        """停止电量监控"""
        self.running = False
        if self.monitor_thread:
            self.monitor_thread.join(timeout=2)
        self.logger.info("电量监控已停止")
    
    def _monitor_loop(self):
        """监控循环"""
        while self.running:
            try:
                self.check_battery_alerts()
                time.sleep(self.check_interval)
            except Exception as e:
                self.logger.error(f"电量监控循环错误: {e}")
                time.sleep(60)  # 出错时等待1分钟后重试